<template>
  <div class="process_pass">
    <one-title title="工序送检合格率" @refreshData="refresh"></one-title>
    <div class="fixed_top_56">
      <div class="multiple_search">
        <div class="search_item">
          <span class="search_label">任务号：</span>
          <div class="search_wrapper">
            <el-select v-model="taskNumber"
                       placeholder="请选择任务号"
                       @change="_treeType"
                       size="small">
              <el-option
                v-for="(item, index) in taskSelect"
                :key="index"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <span class="search_label">选择工序：</span>
          <div class="search_wrapper">
            <el-select v-model="workstageIds"
                       :disabled="taskNumber === ''"
                       multiple
                       collapse-tags
                       placeholder="请选择工序"
                       filterable
                       size="small">
              <el-option
                v-for="(item, index) in workStageSelect"
                :key="index"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <span class="search_label">工序完成日期：</span>
          <div class="search_wrapper date_wrapper">
            <el-date-picker
              v-model="completionDate"
              type="daterange"
              size="small"
              align="right"
              unlink-panels
              :clearable=false
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </div>
        <div class="mes_btn">
          <el-button type="primary"
                     icon="el-icon-search"
                     class="search_btn"
                     @click="init">
          </el-button>
        </div>
      </div>
      <div class="chart_box">
        <div ref="myChart" class="chart_wrapper" v-loading="isLoading"></div>
      </div>
      <div class="table_container">
        <el-table
          :data="listData"
          ref="tableNode"
          max-height="440"
          v-loading="isLoading"
          border
          stripe
          tooltip-effect="dark"
          @sort-change="_sort">
          <mes-column :key="index" v-for="(column, index) in tableColumns" :column="column"></mes-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import tableColumns from './tableColumns'

export default {
  name: 'ProcessPass',
  components: {},
  data() {
    return {
      tableColumns: tableColumns, // 列配置
      isLoading: false, // 加载中
      searchData: {}, // 搜索项
      sortData: {}, // 排序项
      taskNumber: '', // 选中的任务号Id
      workstageIds: [], // 选中的工序Id
      completionDate: [ // 完工日期
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ],
      // 日期格式的快捷键配置项
      pickerOptions: this.$dateConfig.pickerOptions
    }
  },
  computed: {
    // 列表数据
    listData() {
      return this.$store.state.processPass.listData || []
    },
    // 任务工序树
    taskTree() {
      return this.$store.state.processPass.taskTree || []
    },
    // 任务列表
    taskSelect() {
      return [{
        id: '',
        label: '全部'
      }, ...this.taskTree]
    },
    // 工序列表
    workStageSelect() {
      if (!this.taskNumber) {
        let workStageTree = []
        this.taskTree.map(item => {
          if (item.children.length > 0) workStageTree.push(...item.children)
        })
        return workStageTree
      } else {
        return this.taskTree.find(item => item.id === this.taskNumber).children || []
      }
    },
    // 合格数量
    qualifiedNumber() {
      return this.listData.map(item => item.completeQuantity || 0)
    },
    // 不合格数量
    unQualifiedNumber() {
      return this.listData.map(item => item.wasteQuantity || 0)
    },
    // 不合格数量
    passRate() {
      return this.listData.map(item => {
        let num = (item.completeQuantity / item.inputQuantity * 100)
        if (isNaN(num)) num = 0
        return num.toFixed(2)
      })
    },
    // x轴配置
    xAxis() {
      return this.listData.map(item => item.workstageName)
    },
    // 搜索配置
    searchList() {
      return [
        {
          name: 'taskNumber',
          type: 'select',
          label: '任务号',
          value: '',
          treeType: true,
          selectList: this.taskSelect
        },
        {
          name: 'workstageIds',
          type: 'select',
          label: '工序名称',
          value: [],
          multiple: true,
          selectList: this.workStageSelect
        },
        {
          name: 'workStageDate',
          type: 'date',
          label: '日期选择',
          value: '',
        },
      ]
    },
  },
  mounted() {
    this.getTaskTree()
    this.init()
  },
  methods: {
    // 刷新
    refresh() {
      this.completionDate = [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ]
      this.taskNumber = ''
      this.workstageIds = []
      this.init()
    },
    // 初始化
    init() {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/quanlifiedrate',
        data: {},
        module: 'processPass',
        state: 'listData'
      }
      // 是否已选任务号
      if (this.taskNumber) {
        postData.data.taskNumber = this.taskNumber
      }
      if (this.completionDate.length > 0) {
        postData.data.beginWorkStageDate = this.completionDate[0]
        postData.data.endWorkStageDate = this.completionDate[1]
      }
      // 是否已选工序
      if (this.workstageIds.length > 0) {
        postData.data.workstageIds = this.workstageIds.join(',')
      }
      // 是否已选时间
      if (this.completionDate.length > 0) {
        postData.data.beginWorkStageDate = this.completionDate[0]
        postData.data.endWorkStageDate = this.completionDate[1]
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      this.$store.dispatch('saveData', postData).then(res => {
        // 图标滚动缩放设置
        let dataZoom = [
          {
            type: 'slider',
            show: false,
            showDetail: false,
            start: 0,
            end: 100,
            bottom: 10,
            height: 16,
            handleStyle: {
              color: '#fff',
              borderWidth: 2,
              borderColor: '#a1b1c1'
            }
          }
        ]
        let max = 12
        if (res.length >= max) {
          let end = Math.floor(max / res.length * 100)
          dataZoom.forEach(item => {
            item.end = end
            item.show = true
          })
        }
        this.drawLine(dataZoom)
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 获取任务树
    getTaskTree() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workorder/workorder/tasknumberworkstage',
        module: 'processPass',
        state: 'taskTree'
      }).then(res => {
      })
    },
    // 清空工序
    _treeType() {
      this.workstageIds = []
    },
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 绘制图表
    drawLine(dataZoom) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.myChart)
      // 图表配置
      myChart.setOption({
        // 弹框样式
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          padding: 10,
          textStyle: {fontSize: 12},
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
          formatter: (param) => {
            return param[0].name + '<br />' +
              param[0].marker + param[0].seriesName + ': ' + param[0].value + '<br />' +
              param[1].marker + param[1].seriesName + ': ' + param[1].value + '<br />' +
              param[2].marker + param[2].seriesName + ': ' + param[2].value + '%'
          }
        },
        // 缩放，滚动
        dataZoom: dataZoom,
        // 画板边距
        grid: {
          left: '60',
          right: '60',
        },
        // 图标显示
        legend: {
          data: [
            {name: '合格数量'},
            {name: '不合格数量'},
            {name: '合格率'},
          ],
          itemWidth: 24,
          itemHeight: 10,
        },
        xAxis: [
          {
            type: 'category',
            data: this.xAxis,
            // x轴轴线颜色和宽度
            axisLine: {
              lineStyle: {
                color: '#dcdfe6',
                width: 2
              }
            },
            // x轴字体颜色
            axisLabel: {
              show: true,
              textStyle: {
                color: 'rgba(0, 0, 0, 0.65)'
              }
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            // Y轴虚线
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)',
                width: 1,
                type: 'dashed'
              }
            },
            // y轴轴线
            axisLine: {show: false},
            //y轴刻度线
            axisTick: {show: false},
          },
          {
            type: 'value',
            name: '合格率',
            min: 0,
            max: 100,
            splitLine: {
              'show': false,
              lineStyle: {
                color: '#333',
                width: 1,
                type: 'dashed',
              }
            },
            axisLine: {'show': false},
            axisTick: {'show': false},
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        // 数据
        series: [
          {
            name: '合格数量',
            type: 'bar',
            stack: '堆叠',
            barMaxWidth: 160,
            barMinHeight: 10,
            itemStyle: {
              normal: {
                color: '#1890ff',
                opacity: 0.85
              },
            },
            data: this.qualifiedNumber
          },
          {
            name: '不合格数量',
            type: 'bar',
            stack: '堆叠',
            itemStyle: {
              normal: {
                color: '#fbd438',
                opacity: 0.85
              }
            },
            data: this.unQualifiedNumber
          },
          {
            name: '合格率',
            type: 'line',
            yAxisIndex: 1,
            data: this.passRate,
            label: {
              show: false,
              formatter: '{c}%',
              fontSize: 14
            },
            itemStyle: {
              normal: {
                color: '#f04864'
              }
            }
          }
        ]
      })
    }
  }
}
</script>

<style scoped lang="less">
  .process_pass {
    .chart_box {
      padding: 0 20px;
      .chart_wrapper {
        width: 100%;
        height: 500px;
        box-sizing: border-box;
        border: 1px solid #dcdfe6;
        margin-bottom: 20px;
        padding-top: 20px;
      }
    }
    .table_container{
      padding-bottom: 40px;
    }
    .search_wrapper {
      &.date_wrapper {
        flex: 0 0 300px;
        width: 300px;
        .el-date-editor {
          width: 100%;
        }
      }
    }
  }
</style>
